package ccc.hqu.edu.cn.whatmaps;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class CheckService extends Service {
    boolean isrunning = false;
    double[] op_loc = new double[2];
    double[] now_loc = new double[2];
    int mode,radius; //当模式为出围栏模式时，mode值为1；入围栏模式时mode值为2
    public LocationClient mLocationClient = null;
    public BDAbstractLocationListener myListener = new MyLocationListener();
    double dis=0;//距离
    MyLocationData locData=null;
    SharedPreferences preferences;



    double _getRange(double v,double a,double b)
    {
        v=Math.max(v,a);
        v=Math.min(v,b);
        return v;
    }

    double _getLoop(double v,double a,double b)
    {
        while(v > b) v -= b - a;
        while(v < a) v += b - a;
        return v;
    }

    boolean isPointInCircle() //参考百度地图JS库写的代码
    {
        dis=DistanceUtil. getDistance(new LatLng(now_loc[0],now_loc[1]),new LatLng(op_loc[0],op_loc[1]));
        if(dis<=radius) return true;
        else return false;
    }

    // 服务绑定相关代码
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    // 解绑Servcie调用该方法
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public class MyBinder extends Binder {
        CheckService getService() {
            return CheckService.this;
        }
        public int getDistase() {
            return (int)dis;
        }

        public MyLocationData getlocation() {
            return locData;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        int temp=super.onStartCommand(intent, flags, startId);
        if(intent==null) {
            mode=1;
            radius=20;
            op_loc[0]=0;
            op_loc[1]=0;
        }
        else {
            mode = intent.getIntExtra("mode", 1);
            radius = intent.getIntExtra("radius", 20);
            op_loc = intent.getDoubleArrayExtra("op_loc");
        }
        isrunning=true;
        return temp;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        //启动定位
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setIsNeedAddress(true);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        if(!preferences.getBoolean("rule",false)){
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        }else{
            option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        }//设置定位精确度
        option.setNeedDeviceDirect(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        //启动线程，监测是否出入围栏
        isrunning=true;

    }
    @Override
    public void onDestroy()
    {
        isrunning=false;
        super.onDestroy();
    }

    DataCallback dataCallback = null;

    public DataCallback getDataCallback() {
        return dataCallback;
    }

    public void setDataCallback(DataCallback dataCallback) {
        this.dataCallback = dataCallback;
    }
    // 通过回调机制，通知Activity显示对话框
    public interface DataCallback {
        void OutOfFence(); //出围栏对话框
        void InOfFence();  //入围栏对话框
    }



    class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null && (location.getLocType() == 161 || location.getLocType() == 66)) {
                locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        .direction(location.getDirection()).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                if (isrunning == false) return; //服务不运行时无需判断
                now_loc[0] = location.getLatitude();
                now_loc[1] = location.getLongitude();//设定坐标
                if (isPointInCircle() == false && mode == 1) {
                    dataCallback.OutOfFence();
                } else if (isPointInCircle() == true && mode == 2) {
                    dataCallback.InOfFence();
                }
            }
        }
    }

}
